package com.web.controller.store;

import com.domain.store.Question;
import com.domain.store.QuestionItem;
import com.domain.store.Course;
import com.github.pagehelper.PageInfo;
import com.utils.BeanUtil;
import com.web.controller.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/store/questionItem")
public class QuestionItemServlet extends BaseServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String operation = request.getParameter("operation");
        if ("list".equals(operation)){
            //调用查询方法
            list(request,response,null);
        }else if ("toAdd".equals(operation)){
            toAdd(request,response);
        }else if ("save".equals(operation)){
            //添加方法
            try {
                save(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("delete".equals(operation)){
            //删除方法
            delete(request,response);
        }else if ("toEdit".equals(operation)){
            toEdit(request,response);
        }else if ("edit".equals(operation)){
            //修改
            try {
                edit(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if ("saveOrUpdate".equals(operation)){
            try {
                saveOrUpdate(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 修改和添加合并
     * @param request
     * @param response
     */
    private void saveOrUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
       /* //封装数据
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class, "yyyy-MM-dd");
        if (StringUtils.isNoneBlank(questionItem.getId())){
            questionItemService.update(questionItem);
        }else {
            questionItemService.save(questionItem);
        }
        list(request,response);*/
       //包含文件上传功能
        QuestionItem questionItem = null;
        //判断是否支持文件上传操作
        if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //封装数据
            questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);
            //设置旗帜变量
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (StringUtils.isNoneBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            //通过Id判断是啥操作
            if (StringUtils.isNoneBlank(questionItem.getId())){
                questionItemService.update(questionItem,flag);
                //循环数据
                for (FileItem fileItem : fileItems) {
                    //判断当前表单是否为文件表单
                    if (!fileItem.isFormField()){
                        //将文件写入至upload下
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),questionItem.getId()));
                    }
                }
            }else {
                String id = questionItemService.save(questionItem,flag);
                //循环数据
                for (FileItem fileItem : fileItems) {
                    //判断当前表单是否为文件表单
                    if (!fileItem.isFormField()){
                        //将文件写入至upload下
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),id));
                    }
                }
            }
        }
        //重定向
        list(request,response,questionItem.getQuestionId());
    }
    private void edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
       /* request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //封装数据
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class, "yyyy-MM-dd");
        //调用业务层
        questionItemService.update(questionItem);
        //重定向
        list(request,response);*/

       /* if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //封装数据
            QuestionItem questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);

            //设置旗帜变量
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (StringUtils.isNoneBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
            //通过Id判断是啥操作
                questionItemService.update(questionItem,flag);
                //循环数据
                for (FileItem fileItem : fileItems) {
                    //判断当前表单是否为文件表单
                    if (!fileItem.isFormField()){
                        //将文件写入至upload下
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),questionItem.getId()));
                    }
                }
        }
        //重定向
        list(request,response);*/

    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获得数据id
        String id = request.getParameter("id");
        //调用业务层代码
        QuestionItem questionItem = questionItemService.findById(id);
        //将数据存入域中
        request.setAttribute("questionItem",questionItem);
        //修改状态
        request.setAttribute("operation","edit");
        List<Course> all = courseService.findAll();
        request.setAttribute("courseList",all);
        //重定向
        list(request,response,null);
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //得到参数id
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class);
        //调用业务层
        questionItemService.delete(questionItem);
        //重定向
        list(request,response,null);
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //使用工具类,封装bean
        QuestionItem questionItem = BeanUtil.fillBean(request, QuestionItem.class, "yyyy-MM-dd");
        //调用业务层
        questionItemService.save(questionItem);
        //重定向
        list(request,response);*/
        /*request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
       if (ServletFileUpload.isMultipartContent(request)){
            //创建磁盘对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //封装数据
            QuestionItem questionItem = BeanUtil.fillBean(fileItems, QuestionItem.class);

            //设置旗帜变量
            boolean flag = false;
            for (FileItem fileItem : fileItems) {
                //判断当前表单是否为文件表单
                if (StringUtils.isNoneBlank(fileItem.getName())){
                    flag = true;
                    break;
                }
            }
                String id = questionItemService.save(questionItem,flag);
                //循环数据
                for (FileItem fileItem : fileItems) {
                    //判断当前表单是否为文件表单
                    if (!fileItem.isFormField()){
                        //将文件写入至upload下
                        fileItem.write(new File(this.getServletContext().getRealPath("upload"),id));
                }
            }
        }
        //重定向
        list(request,response);*/
    }

    private void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Course> all = courseService.findAll();
        request.setAttribute("courseList",all);
        //转发至添加页面
        request.getRequestDispatcher("/WEB-INF/pages/store/questionItem/add.jsp").forward(request,response);
    }

    private void list(HttpServletRequest request, HttpServletResponse response,String questionId) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取id参数

        if (questionId == null){
            questionId = request.getParameter("questionId");
        }

        request.setAttribute("questionId",questionId);

        if (request.getAttribute("operation") == null){
            request.setAttribute("operation", "save");
        }
        PageInfo all = questionItemService.findAll(questionId,1,100);
        //将数据存至域中
        request.setAttribute("page",all);
        //转发
        request.getRequestDispatcher("/WEB-INF/pages/store/questionItem/list.jsp").forward(request,response);

    }

    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
